package com.ujiuye.filter;

import com.ujiuye.bean.AdminBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = "/*",dispatcherTypes = {DispatcherType.FORWARD,DispatcherType.REQUEST})
public class SecondFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //过滤统一中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //强转获取session的用户信息
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        AdminBean admin = (AdminBean) session.getAttribute("admin");
        //与登录相关页面直接放行
        String url = req.getRequestURI();
        if(url.contains("login")){
            chain.doFilter(req, resp);
        }else {
            if (admin==null){
                resp.sendRedirect("login.jsp");
            }else {
                chain.doFilter(req,resp );
            }
        }

    }

    @Override
    public void destroy() {

    }
}
